package main

/*
#cgo LDFLAGS: -lrt
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>

int open_shm(char* shm_name, int shm_size)
{
	int fd;
	fd = shm_open(shm_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
	if (fd<0) {
		perror("error shm_open");
		return fd;
	}
	int ret = ftruncate(fd, shm_size);
	return fd;
}

int close_shm(char* shm_name)
{
	return shm_unlink(shm_name);
}
*/
import "C"

import (
	"syscall"
	"unsafe"
)

func ShmOpen(ShmName string, ShmSize int) ([]byte, error) {
	var c_shmname = C.CString(ShmName)
	defer C.free(unsafe.Pointer(c_shmname))
	var c_shmsize = C.int(ShmSize)
	c_fd, err := C.open_shm(c_shmname, c_shmsize)
	var fd = int(c_fd)
	if fd < 0 || err != nil {
		return nil, err
	}
	data, err := syscall.Mmap(fd, 0, ShmSize, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)
	return data, err
}

func ShmClose(ShmName string, b []byte) error {
	err := syscall.Munmap(b)

	var c_shmname = C.CString(ShmName)
	defer C.free(unsafe.Pointer(c_shmname))
	C.close_shm(c_shmname)
	return err
}
